from apps.system.user.models import User
from apps.system.user.serializers import TokenModelSerializer
from apps.system.user.dao import UserDao
from apps.common.utils.fileHeader import *
from apps.common.utils.tools import random_str, random_uuid
from datetime import datetime
from rest_framework.authtoken.models import Token
from apps.system.rank.dao import RankDao
from apps.system.team.dao import TeamDao
from apps.chat.message.functions import MessageFun

# 新增用户
def createUser(params):

    # print('新增用户', params)
    if isEmptyStr(params.get('username')):
        if params.get('phone'):
            params['username'] = random_str(4) + params.get('phone')
        else:
            params['username'] = random_uuid()
    else:
        params['username'] = params.get('username')

    if isEmptyStr(params.get('role')):
        params['role'] = 'custom'

    # 设置默认rank级别
    _rank = RankDao().findOneByGrade(0)
    if _rank:
        params['rank'] = _rank.id
    else:
        print('员工级别不存在')

    # 设置默认team级别
    _team = TeamDao().findOneByGrade(0)
    if _team:
        params['team'] = _team.id
    else:
        print('团队级别不存在')

    if isEmptyStr(params.get('checkStatus')):
        params['checkStatus'] = 'PASS'
        
    _user = UserDao().create(params)
    if _user:
        code = 100000 + _user.id
        _user.username = code
        _user.code = code
        _user.incomesCredit = 188
        if not _user.nickname:
            _user.nickname = '用户_' + str(code)
        _user.save()
        MessageFun().sendMessage(None, UserDao().findOneByObjId(_user.id), 'system', {'title': '系统通知', 'content': '鑫珑名品欢迎你您！累计消费满100成为普通会员；分享2位普通会员成为VIP会员，即可享受补贴。'})
    return _user

# 新增管理员
def createAdmin(params):
    _user = UserDao().create(params)
    return _user
def replaceToken(userId):

    old_token = Token.objects.filter(user_id=userId)
    old_token.delete()
    token = Token.objects.create(user_id=userId)

    return token


# 检查推荐人的上级是否有某个用户
def findParentIsExist(user, target):

    if user:
        print('查找', user.id, '的上级，是否存在', target.id)
        if user.parent == target:
            print('存在')
            return True
        else:
            isExist = findParentIsExist(user.parent, target)
            if isExist:
                return True
    else:
        return ''